// api/request.ts
import router from '@/router';
import axios from 'axios';
import type { AxiosInstance, AxiosResponse, AxiosError, InternalAxiosRequestConfig } from 'axios';
import { showFailToast, closeToast, showToast } from 'vant';
import 'vant/es/toast/style';

// 创建 axios 实例
const request: AxiosInstance = axios.create({
  baseURL: '/api',
  timeout: 10000,
  headers: {
    'Content-Type': 'application/json;charset=UTF-8'
  }
});

// 请求拦截器
request.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 添加 token
    const token = localStorage.getItem('token');
    if (token) {
      config.headers.set('Authorization', `${token}`);
    }
    return config;
  },
  (error: AxiosError) => {
    closeToast(); // 关闭加载提示
    showFailToast('请求发送失败');
    return Promise.reject(error);
  }
);

// 响应拦截器
request.interceptors.response.use(
  (response: AxiosResponse) => {
    closeToast(); // 关闭加载提示
    const data = response.data;

    console.log('响应数据：', data.code);

    if (data.code === 200) {
      return data;
    } else {
      console.log('错误信息：', data.msg);

      // 使用 vant 显示错误信息
      showToast({
        message: data.msg || '请求失败',
        duration: 1500,
        teleport: 'body', // 挂载到 body
        type: 'fail' // 明确指定为失败类型
      });

      setTimeout(() => {
        router.push('/login');
      }, 1500);
      
      return Promise.reject(new Error(data.msg || '请求失败'));
    }
  },
  (error: AxiosError) => {
    closeToast(); // 关闭加载提示

    // 根据不同错误类型显示不同提示
    const showMessage = (message: string) => {
      showToast({
        message: message,
        duration: 1500,
        teleport: 'body',
        type: 'fail'
      });
    };

    if (error.response?.status === 401) {
      showMessage('登录已过期，请重新登录');
      localStorage.removeItem('token');
      // 跳转到登录页
      setTimeout(() => {
        window.location.href = '/login';
      }, 1500);
    } else if (error.response?.status === 403) {
      showMessage('权限不足');
    } else if (error.response?.status === 500) {
      showMessage('服务器内部错误');
    } else if (error.code === 'ECONNABORTED' || error.message.includes('timeout')) {
      showMessage('请求超时，请稍后重试');
    } else if (!error.response) {
      showMessage('网络连接异常，请检查网络');
    } else {
      showMessage(error.message || '未知错误');
    }

    return Promise.reject(error);
  }
);

export default request;